<?php

namespace Frieza\Modules\BusinessTool\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\ArticleCounter;
use Doraemon\cache\BlankCounter;
use Doraemon\cache\GuideCounter;
use Doraemon\cache\PhotoCounter;
use Doraemon\cache\Queue;
use Doraemon\cache\TopicCounter;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use hhz\constant\redis\redisKeys;
use Hhz\Redis\otherRedis;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class ContentCounterController
{
    const IGNORE_FILE = '/home/adm_rsync_dir/recounter-ignore.json';
    const ENABLE_TYPES = ['photo', 'article', 'guide', 'blank'];

    public function index(Content $content, Request $request)
    {
        try {
            $ignores = [];
            //从文件中获取
            if (file_exists(self::IGNORE_FILE)) {
                $ignores = json_decode(file_get_contents(self::IGNORE_FILE), true);
            }

            $data = [];
            foreach ($ignores as $key => $val) {
                $data[] = [
                    'type' => $key,
                    'obj_ids' => implode(',', $val),
                ];
            }

            $gridModel = new pGridDataModel($data);

            $grid = Admin::grid($gridModel, function (Grid $grid) {
                $grid->disableActions();
                $grid->disableFilter();
                $grid->disableTools();
                $grid->disablePagination();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->column('type', '内容类型');
                $grid->column('obj_ids', '内容id')->width(800);
            });


            $form = new Form();
            $form->select('type', '内容类型')->required()->options([
                'guide' => 'guide（指南、专题）',
                'article' => 'article（整屋）',
                'blank' => 'blank（文章）',
                'photo' => 'photo（图片、回答）',
            ]);
            $form->text('obj_id', '内容ID')->required()->placeholder('输入objid');

            $form->action('/admin/BusinessTool/contentCounter/addWhite');

            return $content
                ->header('计数修复白名单')
                ->breadcrumb(['text' => '计数修复白名单'])
                ->body($form)
                ->body($grid);

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }

    //添加内容到计数修复白名单
    public function addWhite(Request $request)
    {
        $params = $request->all();

        $type = $params['type'];
        $obj_id = $params['obj_id'];
        if (!$type || !$obj_id) {
            $error = new MessageBag([
                'title' => '缺少参数',
            ]);
            return back()->with(compact('error'))->withInput();
        }

        $ignores = [];
        //从文件中获取
        if (file_exists(self::IGNORE_FILE)) {
            $ignores = json_decode(file_get_contents(self::IGNORE_FILE), true);
        }

        foreach ($ignores as $key => $value) {
            if ($key == $type) {
                $ignores[$key] = array_merge($value, [$obj_id]);
            }
        }

        $keys = array_keys($ignores);
        if (!in_array($type, $keys)) {
            $ignores[$type] = [$obj_id];
        }

        if (file_exists(self::IGNORE_FILE)) {
            try {
                file_put_contents(self::IGNORE_FILE, json_encode($ignores));
                $message = "后台用户：{$_SESSION['name']},对内容类型为{$type}的内容，添加了计数修复白名单，内容id为{$obj_id}";
                Log::info($message, []);
                print_r($ignores);
            } catch (\Exception $exception) {
                $error = new MessageBag([
                    'title' => '修改配置失败',
                ]);
                return back()->with(compact('error'))->withInput();
            }
        }
        return redirect(url("/admin/BusinessTool/contentCounter/index"));
    }

    //设置计数页面
    public function createContentCounterSet(Content $content)
    {
        $form = new Form();
        $form->select('type', '内容类型')->required()->options([
            'photo' => 'photo',
            'guide' => 'guide',
            'question' => 'question',
            'blank' => 'blank',
            'article' => 'article',
        ]);
        $form->text('obj_id', '内容ID/话题名称')->required()->placeholder('输入objid');
        $form->text('like', '点赞计数')->placeholder('输入数字');
        $form->text('favorate', '收藏计数')->placeholder('输入数字');
        $form->text('read', '阅读计数')->placeholder('输入数字');
        $form->text('follow', '关注计数')->placeholder('输入数字');
        $form->text('answer', '话题内容计数')->placeholder('输入数字');

        $form->action('/admin/BusinessTool/contentCounter/setCounterSubmit');

        return $content
            ->header('新建任务')
            ->breadcrumb(['text' => '任务', 'url' => '/admin/BusinessTool/contentCounterSet/create'], ['text' => '新建任务'])
            ->row($form->render());
    }

    //设置计数
    public function setCounterSubmit(Request $request)
    {
        $params = $request->all();

        $type = $params['type'];
        $obj_id = $params['obj_id'];
        //针对话题外的其他内容
        $like = $params['like'];
        $read = $params['read'];
        $favorite = $params['favorate'];
        //针对话题
        $follow = $params['follow'];
        $answer = $params['answer'];
        try {
            switch ($type) {
                case 'photo':
                    if ($like) {
                        $counter[PhotoCounter::ACT_LIKE] = (int)$like;
                    }
                    if ($favorite) {
                        $counter[PhotoCounter::ACT_FAVORITE] = (int)$favorite;
                    }
                    if ($read) {
                        $counter[PhotoCounter::ACT_READ] = (int)$read;
                    }
                    PhotoCounter::setCounter($obj_id, $counter);
                    // 添加到队列，更新搜索图片
                    Queue::insertQueue('Photo/afterAudit', array(
                        'photo_id' => $obj_id
                    ));
                    break;
                case 'guide':
                    if ($like) {
                        $counter[GuideCounter::ACT_LIKE] = (int)$like;
                    }
                    if ($favorite) {
                        $counter[GuideCounter::ACT_FAVORITE] = (int)$favorite;
                    }
                    if ($read) {
                        $counter[GuideCounter::ACT_READ] = (int)$read;
                    }
                    GuideCounter::setCounter($obj_id, $counter);
                    break;
                case 'article':
                    if ($like) {
                        $counter[ArticleCounter::ACT_LIKE] = (int)$like;
                    }
                    if ($favorite) {
                        $counter[ArticleCounter::ACT_FAVORITE] = (int)$favorite;
                    }
                    if ($read) {
                        $counter[ArticleCounter::ACT_READ] = (int)$read;
                    }
                    ArticleCounter::setCounter($obj_id, $counter);
                    Queue::insertQueue('TotalArticle/updateTotalArticle', array('article_id' => $obj_id));
                    break;
                case 'blank':
                    if ($like) {
                        $counter[BlankCounter::ACT_LIKE] = (int)$like;
                    }
                    if ($favorite) {
                        $counter[BlankCounter::ACT_FAVORITE] = (int)$favorite;
                    }
                    if ($read) {
                        $counter[BlankCounter::ACT_READ] = (int)$read;
                    }
                    BlankCounter::setCounter($obj_id, $counter);
                    Queue::insertQueue('TotalArticle/updateTotalArticle', array('article_id' => $obj_id));
                    break;
                case 'question':
                    if ($answer) {
                        $counter[TopicCounter::ANSWER_COUNT] = (int)$answer;
                        //保存虚拟内容数
                        $oKey = redisKeys::KEY_C_OTHER_TOPIC_CONTENT_DUMMY_NUM;
                        $oRedis = new otherRedis($oKey);
                        $oRedis->set($obj_id, (int)$answer);
                    }
                    if ($follow) {
                        $counter[TopicCounter::ACTFLLOW] = (int)$follow;
                    }
                    TopicCounter::setCounter($obj_id, $counter);
                    break;
            }

            //日志记录
            $message = "后台用户：{$_SESSION['name']},对内容类型为{$type}的内容，设置了计数：点赞-{$like}，收藏-{$favorite}，阅读-{$read}，回答数-{$answer}，关注数-{$follow},内容id为{$obj_id}";
            Log::info($message, []);

            return redirect(url("/admin/BusinessTool/contentCounterSet/create"));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }
}
